package cn.xiaye.blog.db.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbUtil {
	private static DbUtil databaseUtil = new DbUtil();
	private Connection conn = null;

	private DbUtil() {

		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/blog", "root", "root");
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static DbUtil getDefaultDatabaseUtil() {
		if (databaseUtil.conn == null) {
			databaseUtil = new DbUtil();
		}
		return databaseUtil;
	}

	public PreparedStatement prepareStatement(String str) {
		System.out.println(str);
		PreparedStatement ps = null;
		try {
			ps = databaseUtil.conn.prepareStatement(str);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ps;
	}

	public void close(PreparedStatement ps) {
		try {
			if (ps != null)
				ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void close(ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
